/**
 * <p>Title: MaterialPackageSvcImpl</p>
 * <p>Description: The Implement of MaterialPackageSvc</p>
 * <p>Copyright: Shanghai Batchsight Pharmaceutical Technologies, Inc. Copyright(c) 2016</p>
 * @author qianpengji
 * @version 1.0
 * <pre>Histroy:
 *       2016-11-22  qianpengji  Create
 *</pre>
*/
package cn.jhg.account.service;

import java.util.List;
import javax.annotation.Resource;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import cn.jhg.account.persist.MaterialPackagePropertyDao;
import cn.jhg.account.entity.AuditTrailObject;
import cn.jhg.account.entity.AuditTrailRecord;
import cn.jhg.account.entity.AuditTrailType;
import cn.jhg.account.entity.MaterialPackage;
import cn.jhg.account.persist.MaterialPackageDao;
import cn.jhg.account.service.AuditTrailSvc;
import cn.jhg.account.util.SequenceProducer;
import cn.jhg.account.util.ServiceResult;

@Transactional
@Service("materialPackageSvc")
public class MaterialPackageSvcImpl implements MaterialPackageSvc{
	
	@Resource
	private MaterialPackageDao materialPackageDao;
	@Resource
	private SequenceProducer sequenceProducer;
	@Resource
	private AuditTrailSvc auditTrailSvc;
	@Resource
	private MaterialPackagePropertyDao materialPackagePropertyDao;
	
	Logger logger = LoggerFactory.getLogger(MaterialPackageSvcImpl.class);

	/**
	 * <p>Function: addPackage </p>
	 * <p>Description: 添加物料件实体</p>
	 * @param MaterialPackage materialPackage 物料件实体
	 * @param int iuid     调用者 id
	 * @param int sid      签名 id
	 * @return ErrorCode   错误代码  ,data 新增的物料件id
	 */
	@Override
	public ServiceResult<Integer> addPackage(MaterialPackage materialPackage, int sid, int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<Integer> serviceResult=new ServiceResult<Integer>();
		try {
			int newId = sequenceProducer.nextval("t_ibcp_material_package");
			materialPackage.setId(newId);
			ObjectId obId=new ObjectId();
			materialPackage.setPropId(obId.toHexString());//转换为16进制字符串
			materialPackageDao.addPackage(materialPackage);
						
			//执行mongoDB数据库的添加
			Document meta=materialPackage.getMetadata();
			materialPackagePropertyDao.addPackage(obId, meta);
			
			serviceResult.setErrorCode(0);
			serviceResult.setData(newId);
			logger.info("[INF223095762] 物料件添加成功");
			
			// 添加审计追踪记录
			AuditTrailRecord atRecord = new AuditTrailRecord();
			atRecord.setSid(sid); // 签名 id
			atRecord.setUid(iuid); // 用户 id
			atRecord.setLid(100);
			atRecord.setTid(AuditTrailType.AddPackage.GetId()); // 审计追踪类型 id
			atRecord.setOtid(AuditTrailObject.MaterialPackage.getId());    // 审计追踪对象 id

			Document metadata = new Document(); // 审计追踪元数据
			metadata.append("Id", materialPackage.getId());
			metadata.append("SeqNo", materialPackage.getSeqNo());
			metadata.append("LabId",  materialPackage.getLabId());
			metadata.append("Quantity",  materialPackage.getQuantity());
			metadata.append("StatId",  materialPackage.getStatId());
			metadata.append("BatId",  materialPackage.getBatId());
			metadata.append("LocStoId",  materialPackage.getLocStoId());
			metadata.append("LocTranId",  materialPackage.getLocTranId());
			metadata.append("PropId",  materialPackage.getPropId());
			atRecord.setMeta(metadata);							
			auditTrailSvc.addRecord(atRecord);
		
			return serviceResult;
		} catch (Exception e) {//try 语句结束
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			serviceResult.setErrorCode(223095779);
			logger.error("[ERR223095779] 物料件添加失败" + e.getMessage());
			return serviceResult;
		}
		
	}

	/**
	 * <p>Function: updatePackage </p>
	 * <p>Description: 更新物料件实体</p>
	 * @param MaterialPackage materialPackage 物料件实体
	 * @param int iuid    调用者 id
	 * @param int sid     签名 id
	 * @return ErrorCode  错误代码
	 */
	@Override
	public ServiceResult<Object> updatePackage(MaterialPackage materialPackage, int sid, int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<Object> serviceResult=new ServiceResult<Object>();
		try {
			int id=materialPackage.getId();
			MaterialPackage mp=materialPackageDao.queryPackageById(id);
			materialPackageDao.updatePackage(materialPackage);				
			
			//执行mongoDB数据库的更新
			ObjectId obId=new ObjectId(mp.getPropId());
			Document meta=materialPackage.getMetadata();
			materialPackagePropertyDao.updatePackage(obId,meta);
			
			serviceResult.setErrorCode(0);
			logger.info("[INF223030682] 物料件更新成功");
			
			// 添加审计追踪记录
			AuditTrailRecord atRecord = new AuditTrailRecord();
			atRecord.setSid(sid); // 签名 id
			atRecord.setUid(iuid); // 用户 id
			atRecord.setLid(100);
			atRecord.setTid(AuditTrailType.UpdatePackage.GetId()); // 审计追踪类型 id
			atRecord.setOtid(AuditTrailObject.MaterialPackage.getId());    // 审计追踪对象 id

			Document metadata = new Document(); // 审计追踪元数据
			metadata.append("Id", materialPackage.getId());
			metadata.append("SeqNo", materialPackage.getSeqNo());
			metadata.append("LabId",  materialPackage.getLabId());
			metadata.append("Quantity",  materialPackage.getQuantity());
			metadata.append("StatId",  materialPackage.getStatId());
			metadata.append("BatId",  materialPackage.getBatId());
			metadata.append("LocStoId",  materialPackage.getLocStoId());
			metadata.append("LocTranId",  materialPackage.getLocTranId());
			metadata.append("PropId",  materialPackage.getPropId());
			atRecord.setMeta(metadata);				
			auditTrailSvc.addRecord(atRecord);		
			return serviceResult;
		} catch (Exception e) {//try 语句结束
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			serviceResult.setErrorCode(223030899);
			logger.error("[ERR223030899] 物料件更新失败" + e.getMessage());
			return serviceResult;
		}
		
	}

	/**
	 * <p>Function: deletePackage </p>
	 * <p>Description: 删除物料件实体</p>
	 * @param int id     物料件id
	 * @param int iuid   调用者 id
	 * @param int sid    签名 id
	 * @return ErrorCode 错误代码
	 */
	@Override
	public ServiceResult<Object> deletePackage(int id, int sid, int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<Object> serviceResult=new ServiceResult<Object>();
		try {
			MaterialPackage materialPackage=materialPackageDao.queryPackageById(id);
			materialPackageDao.deletePackage(id);								
			
			//执行mongoDB数据库的删除			
			ObjectId obId=new ObjectId(materialPackage.getPropId());
			materialPackagePropertyDao.deletePackage(obId);
			
			serviceResult.setErrorCode(0);
			logger.info("[INF223032947] 物料件删除成功");
			
			// 添加审计追踪记录
			AuditTrailRecord atRecord = new AuditTrailRecord();
			atRecord.setSid(sid); // 签名 id
			atRecord.setUid(iuid); // 用户 id
			atRecord.setLid(100);
			atRecord.setTid(AuditTrailType.DeletePackage.GetId()); // 审计追踪类型 id
			atRecord.setOtid(AuditTrailObject.MaterialPackage.getId());    // 审计追踪对象 id

			Document metadata = new Document(); // 审计追踪元数据
			metadata.append("Id", materialPackage.getId());
			metadata.append("SeqNo", materialPackage.getSeqNo());
			metadata.append("LabId",  materialPackage.getLabId());
			metadata.append("Quantity",  materialPackage.getQuantity());
			metadata.append("StatId",  materialPackage.getStatId());
			metadata.append("BatId",  materialPackage.getBatId());
			metadata.append("LocStoId",  materialPackage.getLocStoId());
			metadata.append("LocTranId",  materialPackage.getLocTranId());
			metadata.append("PropId",  materialPackage.getPropId());
			atRecord.setMeta(metadata);				
			auditTrailSvc.addRecord(atRecord);
			return serviceResult;
		} catch (Exception e) {//try 语句结束
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			serviceResult.setErrorCode(223032866);
			logger.error("[ERR223032866] 物料件删除失败" + e.getMessage());
			return serviceResult;
		}

	}

	/**
	 * <p>Function: queryPackageById </p>
	 * <p>Description: 根据物料件id查询物料件实体</p>
	 * @param int id       物料件id
	 * @param int iuid     调用者 id
	 * @return ErrorCode   错误代码,data 物料件实体
	 */
	@Override
	public ServiceResult<MaterialPackage> queryPackageById(int id, int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<MaterialPackage> serviceResult=new ServiceResult<MaterialPackage>();
		try {
			MaterialPackage materialPackage=materialPackageDao.queryPackageById(id);	
			//执行mongoDB数据库的查询	
			ObjectId obId=new ObjectId(materialPackage.getPropId());
			Document doc=materialPackagePropertyDao.queryPackage(obId);				
			materialPackage.setMetadata(doc);
			//封装返回参数
			serviceResult.setData(materialPackage);
			serviceResult.setErrorCode(0);
			logger.info("[INF223089872] 根据id查询物料件成功");
			return serviceResult;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			serviceResult.setErrorCode(223199403);
			logger.error("[ERR223199403] 根据id查询物料件失败" + e.getMessage());
			return serviceResult;
		}

	}

	/**
	 * <p>Function: queryPackageByLabel </p>
	 * <p>Description: 根据标签id查询物料件实体</p>
	 * @param int labId    标签id
	 * @param int iuid     调用者 id
	 * @return ErrorCode   错误代码,data 物料件实体
	 */
	@Override
	public ServiceResult<MaterialPackage> queryPackageByLabel(int labId, int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<MaterialPackage> serviceResult=new ServiceResult<MaterialPackage>();
		try {
			MaterialPackage materialPackage=materialPackageDao.queryPackageByLabel(labId);
			if(materialPackage==null){
				serviceResult.setErrorCode(223199405);
				logger.error("[ERR223199405] 物料件不存在");
			}else{
				//执行mongoDB数据库的查询
				ObjectId obId=new ObjectId(materialPackage.getPropId());
				Document doc=materialPackagePropertyDao.queryPackage(obId);				
				materialPackage.setMetadata(doc);								
				
				serviceResult.setErrorCode(0);
				logger.info("[INF223090151] 根据标签id查询物料件成功");
			}
			return serviceResult;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			serviceResult.setErrorCode(223090164);
			logger.error("[ERR223090164] 根据标签id查询物料件失败" + e.getMessage());
			return serviceResult;
		}
	}

	/**
	 * <p>Function: findPackage </p>
	 * <p>Description: 按条件查找物料件id集合</p>
	 * @param batId			批次id（等于0表示所有）
	 * @param seq			顺序号（等于空表示所有）
	 * @param locStoId		存储位置id（等于0表示所有）
	 * @param locTranId		转移位置id（等于0表示所有）
	 * @param statId		状态id（等于0表示所有）
	 * @param iuid			调用者id
	 * @return ErrorCode 错误代码,data 物料件实体id集合
	 */
	@Override
	public ServiceResult<List<Integer>> findPackage(int batId, String seq, int locStoId, int locTranId, int statId,
			int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<List<Integer>> serviceResult=new ServiceResult<List<Integer>>();
		MaterialPackage materialPackage=new MaterialPackage();
		String newSeq = "%" + seq + "%";//设置为模糊查询
		materialPackage.setBatId(batId);
		materialPackage.setSeqNo(newSeq);
		materialPackage.setLocStoId(locStoId);
		materialPackage.setLocTranId(locTranId);
		materialPackage.setStatId(statId);
		try {
			List<Integer> list=materialPackageDao.findPackage(materialPackage);
			serviceResult.setData(list);
			serviceResult.setErrorCode(0);
			logger.info("[INF223090171] 按条件查找物料件id成功");
			return serviceResult;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			serviceResult.setErrorCode(223090493);
			logger.error("[ERR223090493] 按条件查找物料件id失败" + e.getMessage());
			return serviceResult;
		}
		
	}

	/**
	 * <p>Function: findPackageDetail </p>
	 * <p>Description: 按条件查找物料件实体</p>
	 * @param batId			批次id（等于0表示所有）
	 * @param seq			顺序号（等于空表示所有）
	 * @param locStoId		存储位置id（等于0表示所有）
	 * @param locTranId		转移位置id（等于0表示所有）
	 * @param statId		状态id（等于0表示所有）
	 * @param iuid			调用者id
	 * @return ErrorCode 错误代码,data 物料件实体id集合
	 */
	@Override
	public ServiceResult<List<MaterialPackage>> findPackageDetail(int batId, String seq, int locStoId, int locTranId,
			int statId, int iuid) {
		// TODO Auto-generated method stub
		ServiceResult<List<MaterialPackage>> serviceResult=new ServiceResult<List<MaterialPackage>>();
		MaterialPackage materialPackage=new MaterialPackage();
		String newSeq = "%" + seq + "%";//设置为模糊查询
		materialPackage.setBatId(batId);
		materialPackage.setSeqNo(newSeq);
		materialPackage.setLocStoId(locStoId);
		materialPackage.setLocTranId(locTranId);
		materialPackage.setStatId(statId);
		try {
			List<MaterialPackage> list=materialPackageDao.findPackageDetail(materialPackage);
			serviceResult.setData(list);
			serviceResult.setErrorCode(0);
			logger.info("[INF223090515] 按条件查找物料件成功");				
			return serviceResult;
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			serviceResult.setErrorCode(223090715);
			logger.error("[ERR223090715] 按条件查找物料件失败" + e.getMessage());
			return serviceResult;
		}
		
	}

}
